#include <VirtualWire.h>

volatile unsigned long steeringValue = 511;
volatile unsigned long speedValue = 511;

// RF Received Message (char and unsigned int)
char ReceivedMessage[8]; 
volatile unsigned long ReceviedValue = 0;

void setup()
{
    Serial.begin(9600);    

    // Initialise the IO and ISR
    vw_set_ptt_inverted(true);    // Required for RX Link Module
    vw_setup(2000);                   // Bits per sec
    vw_set_rx_pin(23);           // We will be receiving on pin 23 (Mega) ie the RX pin from the module connects to this pin. 
    vw_rx_start();                      // Start the receiver 
}

void loop()
{
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) // check to see if anything has been received
  {
    int i;
    // Message with a good checksum received. 
    for (i = 0; i < buflen; i++)
    {
       //Serial.print((unsigned int)buf[i]);  // the received data is stored in buffer
       // Fill Sensor1CharMsg Char array with corresponding chars from buffer.   
       ReceivedMessage[i] = char(buf[i]);
    }
    // Null terminate the char array
    // This needs to be done otherwise problems will occur
    // when the incoming messages has less digits than the
    // one before. 
    ReceivedMessage[buflen] = '\0';
    Serial.print("BUFFLEN: ");
    Serial.print(buflen);
    Serial.println();
    // Convert ReceivedMessage Char array to integer
    ReceviedValue = atoi(ReceivedMessage);
    Serial.print("Message Text: ");
    Serial.print(ReceivedMessage);
    Serial.println();
    Serial.print("Message Value: ");
    Serial.print(ReceviedValue);
    Serial.println();
    
    steeringValue = ((ReceviedValue>>10)&0x3FF);
    speedValue = ReceviedValue&0x3FF;
    
    // DEBUG
    Serial.print("Steering Value: ");
    Serial.print(steeringValue);
    Serial.println();
    Serial.print("Speed Value: ");
    Serial.print(speedValue);
    Serial.println();
    // END DEBUG
   }
   else
   {
     Serial.print("No data received!");
     Serial.println();
   }
   delay(1000);
}

